package passport

import (
	"crypto/md5"
	"fmt"
	"strconv"

	"yundata-service/internal"
	"yundata-service/util"

	"github.com/mojocn/base64Captcha"

	lv "yundata-service/pkg/validation/passport"

	um "yundata-service/pkg/model/ucenter"
)

type LoginAction struct {
	internal.ActionModel
}

func (ac *LoginAction) DoLogin() {
	loginForm := &lv.LoginValidate{}

	c := ac.Ctx
	if err := c.ShouldBindJSON(loginForm); err != nil {
		ac.Fail(err.Error())
		return
	}

	db := internal.GDb
	user := &um.User{}

	hashedPassword := fmt.Sprintf("%x", md5.Sum([]byte(loginForm.Password)))
	// where := map[string]interface{}{"nickname": loginForm.Username, "password": hashedPassword}
	// fmt.Println(where)

	db.Debug().Model(user).Where("username = ?", loginForm.Username).Where("password = ?", hashedPassword).First(user)
	// 打印sql

	if user.ID <= 0 {
		ac.Fail("账号或密码错误")
		return
	}

	uid := strconv.Itoa(int(user.ID)) // Convert user.ID to int
	token, _ := util.CreateToken(uid, "hongsi")

	type Data struct {
		Us    *um.User `json:"user"`
		Token string   `json:"token"`
	}
	resData := Data{user, token}

	ac.Success("登录成功", resData)
}

// 生成base64位的验证码图片
func (ac *LoginAction) Captcha() {

	// 字符,公式,验证码配置
	var configD = base64Captcha.DriverDigit{
		Height:   80,
		Width:    240,
		Length:   5,
		MaxSkew:  0.7,
		DotCount: 80,
	}

	// 生成验证码
	c := base64Captcha.NewCaptcha(&configD, base64Captcha.DefaultMemStore)
	id, b64s, answer, err := c.Generate()
	if err != nil {
		ac.Fail(err.Error())
		return
	}

	// 设置返回值
	type Data struct {
		CaptchaKey    string `json:"captchaKey"`
		CaptchaBase64 string `json:"captchaBase64"`
		Answer        string `json:"answer"`
	}
	resData := Data{id, b64s, answer}

	ac.Success("验证码生成成功", resData)
}
